<?php
/**
 * Nordic Repository
 * 
 * LICENSE
 * 
 * The new BSD license is applied on this source-file. For further
 * information please visit http://license.nordic-dev.de/newbsd.txt
 * or send an email to andre.moelle@gmail.com.
 */

/**
 * Necessary includes.
 */
Zend_Loader::loadClass('Zend_Db_Table');

/**
 * Model for the tokens.
 * 
 * @category   Nordic
 * @package    Nordic_Auth
 * @copyright  2007 Nordic Development
 * @license    http://license.nordic-dev.de/newbsd.txt (New-BSD license)
 * @author     Andre Moelle <andre.moelle@gmail.com>
 * @version    $Id: Token.php 3 2007-07-08 09:21:42Z andre.moelle $
 */
class Nordic_Auth_Model_Token extends Zend_Db_Table
{
	/**
	 * @see Zend_Db_Table::_name
	 */
	protected $_name = 'auth_token';
	
	/**
	 * Deletes a token.
	 * 
	 * @param integer $id id of the user
	 * @return integer
	 */
	public function deleteToken ($id)
	{
		return $this->_db->query(
			'DELETE FROM ' . $this->_name . ' ' .
			'WHERE id = ?',
			array(
				$id
			)
		)->rowCount();
	}
	
	/**
	 * Returns the token-information about an user.
	 * 
	 * @param integer $id id of the token-user
	 * @return array
	 */
	public function findToken ($id)
	{
		$select = $this->_db->select();
		$select->from($this->_name);
		$select->where('id = ?', $id);
		$select->where('timeout > NOW()');
		$select->limit(1);
		
		return $select->query()->fetch();
	}
	
	/**
	 * Sets a token in the table.
	 * 
	 * This method uses the REPLACE INTO, because it fits better than
	 * UPDATEing or INSERTing.
	 * 
	 * @param integer $id id of the user
	 * @param string $identifier identifier
	 * @param string $token token
	 * @param integer $timeout time (in seconds) which are added to the actual time
	 * @return integer
	 */
	public function setToken ($id, $identifier, $token, $timeout)
	{
		return $this->_db->query(
			'REPLACE INTO ' . $this->_name . ' (id, identifier, token, timeout) ' .
			'VALUES (?, ?, ?, ?)',
			array(
				$id,
				$identifier,
				$token,
				date('Y-m-d H:i:s', time() + $timeout)
			)
		)->rowCount();
	}
}
?>